package com.kelp.codetoolkit.actions

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.ui.Messages
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.util.PsiUtilBase

/**
 * @author: liuyuebai
 * @date: 2025/8/29 11:31
 * @description:
 */
class EnumToCommentAction: AnAction() {
    override fun actionPerformed(e: AnActionEvent) {
        val project = e.project?: return
        val psiFile = e.getData(CommonDataKeys.PSI_FILE)?: return
        val psiJavaFile = psiFile as PsiJavaFile
        val enumClass = psiJavaFile.classes[0]
        if (!enumClass.isEnum){
            Messages.showErrorDialog(project, "Enum Class is not NULL", "Error")
            return
        }
        // 生成键值对（不换行，以分号分隔）
        val result = buildString {
            enumClass.fields.filterIsInstance<PsiEnumConstant>().forEachIndexed { index, enumConstant ->
                val args = enumConstant.argumentList?.expressions?: return@forEachIndexed
                if (args.size >= 2) {
                    val key = getValueFromExpression(args[0])
                    val value = getValueFromExpression(args[1])
                    if (key!= null && value!= null) {
                        // 拼接键值对
                        append("$key-$value")
                        // 除了最后一个元素，都添加分号分隔
                        if (index!= enumClass.fields.filterIsInstance<PsiEnumConstant>().lastIndex) {
                            append(";")
                        }
                    }
                }
            }
        }
        if (result.isEmpty()){
            Messages.showErrorDialog(project, "Enum Class is not NULL", "Error")
            return
        }
        Messages.showInfoMessage(project, result, "Result")
    }

    // 从表达式中提取值
    private fun getValueFromExpression(expression: Any?): String? {
        return when (expression) {
            is PsiLiteralExpression -> expression.value?.toString()
            else -> null
        }
    }
}